package com.wx.lambda.ii.chapter2;



import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 第二章试验
 * 对苹果的集合，进行过滤 根据颜色或者重量
 *
 * @author wang.xun
 * @date 2023/12/05
 */

public class Chapter2Test {
    public static void main(String[] args) {
        ArrayList<Apple> apples = new ArrayList<>();
        initData(apples);
        // 使用不通谓词实现
        filter1(apples,new ApplePredicateColorImpl());
        // 直接使用lambda表达式
        filter2(apples,apple -> apple.getColor().equals("green"));

        // 直接使用lambda表达式
        filter3(apples,apple -> apple.getColor().equals("green"));


    }

    static void filter1(List<Apple> apples,ApplePredicate applePredicate){
        ArrayList<Apple> filter = new ArrayList<>();

        for (Apple apple : apples) {
            if (applePredicate.test(apple)) {
                filter.add(apple);
            }
        }

        System.out.printf("filter1 : 处理后的集合 %s%n",filter);
    };

    static void filter2(List<Apple> apples,ApplePredicate applePredicate){
        ArrayList<Apple> filter = new ArrayList<>();

        for (Apple apple : apples) {
            if (applePredicate.test(apple)) {
                filter.add(apple);
            }
        }

        System.out.printf("filter2 : 处理后的集合 %s%n",filter);
    };

    static void filter3(List<Apple> apples, Predicate<Apple> predicate){
        List<Apple> collect = apples.stream().filter(predicate).collect(Collectors.toList());

        System.out.printf("filter3 : 处理后的集合 %s%n",collect);
    };


    public static void initData(List<Apple> apples) {
    /*
      新建一个List 插入 十条 Apple 对象
     */

        for (int i = 0; i < 10; i++) {
            Apple apple = new Apple();
            apple.setColor("red");
            apple.setWeight(1.0*i);
            apples.add(apple);
        }
        for (int i = 0; i < 10; i++) {
            Apple apple = new Apple();
            apple.setColor("green");
            apple.setWeight(1.0 * i);
            apples.add(apple);
        }

    }





    /**
     * 苹果谓词
     *
     * @author wang.xun
     * @date 2023/12/05
     */
    @FunctionalInterface
    interface ApplePredicate{
        boolean test(Apple apple);
    }

    static class ApplePredicateColorImpl implements ApplePredicate{

        @Override
        public boolean test(Apple apple) {
            return apple.getColor().equals("red");
        }
    }
}
